package statsyslogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/mr"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/stat"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"
	"time"

	"navi-mumbai/app/rpc/stat/internal/svc"
	"navi-mumbai/app/rpc/stat/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserDailyDepositStatLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserDailyDepositStatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDailyDepositStatLogic {
	return &UserDailyDepositStatLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 每日用户充值统计
func (l *UserDailyDepositStatLogic) UserDailyDepositStat(in *pb.UserDailyDepositStatReq) (*pb.UserDailyDepositStatResp, error) {
	defer utils.RecoverPanic()

	var start, end *time.Time
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		start = &t
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		end = &t
	}

	var ds stat.UserDepositDailyStat
	ds.StatDay, _ = strconv.ParseInt(start.Format(dbkey.DateFormat2), 10, 64)
	ds.PayChannelId = in.PayChannelId
	var err error

	err = mr.Finish(func() error {
		// 充值金额
		ds.DepositAmount, err = l.svcCtx.UserDepositFlowModel.SumAmount(l.ctx, in.PayChannelId, start, end)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
		}
		l.Logger.Infof("UserDailyDepositStat. DepositAmount: %+v", ds.DepositAmount)
		return nil
	},
		func() error {
			// 充值订单数
			ds.DepositCount, err = l.svcCtx.UserDepositFlowModel.CountSuccessFlow(l.ctx, in.PayChannelId, start, end)
			if err != nil {
				l.Logger.Errorf("err == ", zap.Error(err))
			}
			return nil
		},
		func() error {
			// 充值人数
			ds.DepositUserCount, err = l.svcCtx.UserDepositFlowModel.CountSuccessUser(l.ctx, in.PayChannelId, start, end)
			if err != nil {
				l.Logger.Errorf("err == ", zap.Error(err))
			}
			return nil
		})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
	}

	//
	_, err = l.svcCtx.UserDepositDailyStatModel.Insert(l.ctx, &ds)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	return &pb.UserDailyDepositStatResp{}, nil
}
